//
//  XHRScrollPictureView.m
//  CollectionView实现无限分页
//
//  Created by 胥鸿儒 on 16/5/15.
//  Copyright © 2016年 xuhongru. All rights reserved.
//

#import "XHRScrollPictureView.h"
#import "XHRPictureDriftLayout.h"
#import "XHRPictureDriftCell.h"
#define XHRSize (self.collectionView.frame.size)
#define XHRContentX (self.collectionView.contentOffset.x)
//define this constant if you want to use Masonry without the 'mas_' prefix
#define MAS_SHORTHAND
//define this constant if you want to enable auto-boxing for default syntax
#define MAS_SHORTHAND_GLOBALS
#import "Masonry.h"
@interface XHRScrollPictureView()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate>
{
    NSArray *_pictureArray;
}

@property(nonatomic,weak)UICollectionView *pictureDriftView;
@property(nonatomic,weak)UICollectionView *collectionView;

@property(nonatomic,assign)NSInteger itemsCount;

@property(nonatomic,weak)UIPageControl *pageControl;

@property(nonatomic,weak)NSTimer *timer;


@property(nonatomic,strong)NSArray *pictureArray;
@property(nonatomic,strong)XHRPictureDriftLayout *pictureDriftLayout;
- (NSArray *)pictureArray;

- (UIColor *)currentColor;
- (UIColor *)otherColor;
- (BOOL)autoScroll;

@end

static NSString *const ID = @"PictureDrift";

static CGFloat const defaultTimeInerval = 2.0;

@implementation XHRScrollPictureView
#pragma mark - 设置一些默认属性
- (CGFloat)timeInterval
{
    if ([self.delegate respondsToSelector:@selector(timeIntervalOfPagingToNextPageInScrollPictureView:)]) {
        return [self.delegate timeIntervalOfPagingToNextPageInScrollPictureView:self];
    }
    else return defaultTimeInerval;
}
- (UIColor *)currentColor
{
    if ([self.delegate respondsToSelector:@selector(currentColorOfPageControlInScrollPictureView:)]) {
        return [self.delegate currentColorOfPageControlInScrollPictureView:self];
    }
    else return [UIColor greenColor];
}
- (UIColor *)otherColor
{
    if ([self.delegate respondsToSelector:@selector(otherColorOfPageControlInScrollPictureView:)]) {
        return [self.delegate otherColorOfPageControlInScrollPictureView:self];
    }
    else
       return [UIColor redColor];
}
- (BOOL)autoScroll
{
    if ([self.delegate respondsToSelector:@selector(scrollPictureViewShouldAutoScroll:)]) {
        return  [self.delegate scrollPictureViewShouldAutoScroll:self];
    }
    else return YES;
}
- (NSArray *)pictureArray
{
    return [self.delegate contentOfPictureInScrollPictureView];
}
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        if ([NSStringFromCGRect(frame) isEqualToString:NSStringFromCGRect(CGRectMake(0, 0, 0, 0))]) {
            self.frame = CGRectMake(0, 0, 375, 150);
        }
    }
    return self;
}
+ (instancetype)scrollPictureViewWithFrame:(CGRect)frame
{
    XHRScrollPictureView *scrollPictureView = [[self alloc]initWithFrame:frame];
    return scrollPictureView;
}

#pragma mark - 初始化collectionView
- (void)setupUI
{
    //初始化layout
    XHRPictureDriftLayout *pictureDriftLayout = [[XHRPictureDriftLayout alloc]init];
    self.pictureDriftLayout = pictureDriftLayout;
    
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.bounds collectionViewLayout:pictureDriftLayout];
    NSLog(@"%@",NSStringFromCGRect(self.bounds));
    self.collectionView = collectionView;
    
    [self addSubview:collectionView];

    //初始化collectionView
    collectionView.backgroundColor = [UIColor clearColor];
    [collectionView registerClass:[XHRPictureDriftCell class] forCellWithReuseIdentifier:ID];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.alwaysBounceVertical = NO;
    collectionView.alwaysBounceHorizontal = NO;
    collectionView.pagingEnabled = YES;
    
    
    if (self.pictureArray.count == 1) collectionView.scrollEnabled = NO;
    else self.collectionView.scrollEnabled = YES;
}

#pragma mark - 初始化pageControl
- (void)setupPageControl
{
    //实例化pageControl
    UIPageControl *pageControl = [[UIPageControl alloc]init];
    self.pageControl = pageControl;
    
    [self addSubview:pageControl];
    
    //初始化pageControl
    pageControl.hidesForSinglePage = YES;
    pageControl.currentPageIndicatorTintColor = self.currentColor;
    pageControl.pageIndicatorTintColor = self.otherColor;
    pageControl.hidden = self.isShowPageControl;
    self.pageControl.numberOfPages = self.pictureArray.count;
}

#pragma mark - 代理的设置
- (void)setDelegate:(id<XHRScrollPictureViewDelegate>)delegate
{
    _delegate = delegate;
    
    self.pictureArray = [delegate contentOfPictureInScrollPictureView];
    
    [self setupUI];
    [self setupPageControl];
    
    self.itemsCount = _pictureArray.count > 1?_pictureArray.count * 1000:_pictureArray.count;

    
    if (self.autoScroll && delegate)
    {
        [self startTimer];
    }
}
#pragma mark - collectionView Data Source
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.itemsCount;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    XHRPictureDriftCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
    cell.imageName = self.pictureArray[indexPath.item % self.pictureArray.count];
    
    return cell;
}

#pragma mark - 布局子控件
- (void)layoutSubviews
{
    [super layoutSubviews];
    //设置pageControl约束
    [self.pageControl makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.bottom.offset(-5);
    }];

    self.collectionView.frame = CGRectMake(0, 0, self.xhr_Width, self.xhr_Height);
    if (self.collectionView.contentOffset.x == 0 && self.itemsCount) {
        NSInteger index = self.itemsCount * 0.5;
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
}

#pragma mark - 实现自动分页方法
- (void)nextPage
{
    NSInteger pageNumber = (NSInteger)(XHRContentX / XHRSize.width);
    if (pageNumber + 1 < self.itemsCount) {
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:pageNumber + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionRight  animated:YES];
    }
    else
    {
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.itemsCount * 0.5  inSection:0] atScrollPosition:UICollectionViewScrollPositionRight  animated:NO];
    }

}
#pragma mark - 监听collectionView的滚动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.pageControl.currentPage = ((int)(XHRContentX / XHRSize.width + 0.5)) % self.pictureArray.count;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self stopTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.autoScroll) {
        [self startTimer];
    }
}

#pragma mark - 设置定时器
- (void)startTimer
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:self.timeInterval target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
}

- (void)stopTimer
{
    [self.timer invalidate];
    self.timer = nil;
}
@end
